package com.richard.base.net.model.api

import com.ks.component.net.NetConstants.HTTP_REQUEST_TIMEOUT
import com.richard.base.BuildConfig
import com.richard.base.net.common.NetComponent
import com.richard.base.net.interceptors.ChangeBaseUrlInterceptor
import com.richard.base.net.interceptors.HeaderInterceptor
import com.richard.base.net.utils.SSLSocketFactoryUtils
import com.richard.base.net.api.BaseRetrofitClient
import com.richard.base.net.interceptors.BasicParamsInterceptor
import com.richard.base.net.interceptors.CacheInterceptor
import com.richard.base.net.ssl.TrustAllSSLSocketClient
import com.richard.base.util.FileUtil
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.io.File
import java.util.concurrent.TimeUnit
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.X509TrustManager

/**
 ***************************************
 * 项目名称:base
 * @Author wuzhiguo
 * 邮箱：wuzhiguo@ksjgs.com
 * 创建时间: 2019/12/31     10:53 AM
 * 用途：相当于 kaishu app 的 ksApiManager ，只是 抽离了。
 ***************************************
 *
 */
object KsRetrofitClient : BaseRetrofitClient() {

    /**
     * 是否需要自定义证书验证
     * @return Boolean
     */
    fun isNeedSSL(): Boolean {
        return NetComponent.isNeedSSL
    }

    override fun baseUrl(): String {
        return NetComponent.baseUrl
    }

    //    private const val KEY_IS_NEED_SSL = "key_is_need_ssl"
    //线上
    const val ENV_RELEASE = 3

//    var isNeedSsl by Preference(KEY_IS_NEED_SSL, true)

    override fun handleBuilder(builder: OkHttpClient.Builder) {
        //缓存文件路径
        val file = File(FileUtil.rootCachePath, "okhttp_cache")
        //缓存文件大小为20MB
        val okCache = Cache(file, 20 * 1024 * 1024)

        builder.connectTimeout(HTTP_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS)
            .readTimeout(HTTP_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS)
            .writeTimeout(HTTP_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS)
            .addInterceptor(BasicParamsInterceptor())
            .addInterceptor(ChangeBaseUrlInterceptor())
//                .addInterceptor(DynamicTimeoutInterceptor())
//                .addInterceptor(CommonCodeInterceptor())
            .addInterceptor(CacheInterceptor.OfflineCacheInterceptor)
            .addNetworkInterceptor(CacheInterceptor.NetCacheInterceptor)
            .cache(okCache)
            .addInterceptor(HeaderInterceptor()).apply {
                if (BuildConfig.DEBUG) {
                    addInterceptor(HttpLoggingInterceptor().apply {
                        level = HttpLoggingInterceptor.Level.BODY
                    })
                }

                if (isNeedSSL()) {
                    var instance = SSLSocketFactoryUtils.instance
                    val sSlSocketFactoryByPaths: SSLSocketFactory? =
                        instance.getSSlSocketFrctoryByPaths()
                    var trustManagers = instance.trustManagers
                    if (sSlSocketFactoryByPaths != null && trustManagers.isNotEmpty()) {
                       sslSocketFactory(
                            sSlSocketFactoryByPaths,
                            instance.trustManagers[0] as X509TrustManager
                        )
                        hostnameVerifier(HostnameVerifier { s, sslSession -> true })
                    }
                } else {
                    sslSocketFactory(
                        TrustAllSSLSocketClient.getSSLSocketFactory(),
                        TrustAllSSLSocketClient.getX509TrustManager()
                    )
                    hostnameVerifier(TrustAllSSLSocketClient.getHostnameVerifier())
                }

            }
    }


}